<template>
    <div :key="modalKey">
        <el-row>
            <el-row class="pt20">
                <el-tabs type="border-card" v-model="activeKey" @tab-click="handleClick">
                    <el-tab-pane name="all" :label="'全部(' + all_num + ')'">
                    </el-tab-pane>
                    <el-tab-pane name="listen" :label="'听力(' + listen_num + ')'">
                    </el-tab-pane>
                    <el-tab-pane name="read" :label="'阅读(' + read_num + ')'">
                    </el-tab-pane>
                    <el-tab-pane name="record" :label="'录音(' + record_num + ')'">
                    </el-tab-pane>
                    <el-tab-pane name="create" :label="'创作(' + create_num + ')'">
                    </el-tab-pane>
                </el-tabs>
            </el-row>
            <el-table :data="tableData" v-loading="loading" size="mini" :show-header="true"
                style="width: 100%;margin-bottom: 20px;" :row-key="handleRowkey" border stripe default-expand-all>
                <el-table-column prop="title" label="课件" header-align="center" align="center">
                    <template slot-scope="scope">
                        <div style="display: flex;">
                            <div v-if="scope.row.task_type == 'create'">
                              <img src="@/assets/img/kanke/task/createimage.png" alt="暂无图片"
                                   style="vertical-align: middle;width: 80px; height: 58px; margin-right: 10px;">
                            </div>
                            <div v-else-if="isArray(scope.row.cover_url)">
                                <img :src="scope.row.cover_url[0].cover_url" alt="暂无图片"
                                    style="vertical-align: middle;width: 80px; height: 58px; margin-right: 10px;">
                            </div>
                            <div v-else>
                                <img :src="scope.row.cover_url" alt="暂无图片"
                                    style="vertical-align: middle;width: 80px; height: 58px; margin-right: 10px;">
                            </div>

                            <div style="">
                                <p style="margin-top: 0;text-align: left;font-weight: bold;font-size: 15px;">{{
                                    scope.row.title }}</p>
                                <p style="margin-bottom: 0;text-align: left;font-size: 13px;"
                                    v-if="scope.row.task_type == 'create'">
                                    <el-tag effect="dark"
                                        style="display: flex;height: 20px;width:50px;text-align: center;  align-items: center;background-color: #8300FE;border:0;">
                                        创作
                                    </el-tag>
                                </p>
                                <p style="margin-bottom: 0;text-align: left;font-size: 13px;"
                                    v-else-if="scope.row.task_type == 'listen'">
                                    <el-tag effect="dark"
                                        style="display: flex;height: 20px;width:50px;text-align: center;align-items: center;background-color: #F59A23;border:0;">
                                        听力
                                    </el-tag>
                                </p>
                                <p style="margin-bottom: 0;text-align: left;font-size: 13px;"
                                    v-else-if="scope.row.task_type == 'read'">
                                    <el-tag effect="dark"
                                        style="display: flex;height: 20px;width:50px;text-align: center;align-items: center;background-color: #63A102;border:0;">
                                        阅读
                                    </el-tag>
                                </p>
                                <p style="margin-bottom: 0;text-align: left;font-size: 13px;"
                                    v-else-if="scope.row.task_type == 'record'">
                                    <el-tag effect="dark"
                                        style="display: flex;height: 20px;width:50px;text-align: center;align-items: center;background-color: #03A7F0;border:0;">
                                        录音
                                    </el-tag>
                                </p>
                            </div>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="state" label="排序(学生展示排序)" header-align="center" align="center" v-if="isShow(['kanke:exercises:task:content-add','kanke:exercises:task:content-del','kanke:exercises:task:content-sync'])">
                    <template slot-scope="scope">

<!--                        <el-link>-->
<!--                            {{scope.row.sort}}-->
<!--                        </el-link>-->


                        <el-link style="font-size: 27px;color: #03A7F0;"  @click="sort(scope.row,1)">
                            <i class="el-icon-top"></i>
                        </el-link>
                        <el-link style="font-size: 27px;color:#af4545;"  @click="sort(scope.row,2)" >
                            <i class="el-icon-bottom"></i>
                        </el-link>
                    </template>
                </el-table-column>
                <el-table-column prop="state" label="操作" header-align="center" align="center" v-if="isShow(['kanke:exercises:task:content-add','kanke:exercises:task:content-del','kanke:exercises:task:content-sync'])">
                    <template slot-scope="scope">
                        <!--
                        <pers-button type="text" perms="kanke:exercises:task:content-edit"  @click="handleEdit(scope.row)" label="编辑"></pers-button>
                        -->
                        <pers-button type="text" perms="kanke:exercises:task:content-del"  @click="handleDel(scope.row)" label="删除"></pers-button>
                        <pers-button type="text" perms="kanke:exercises:task:content-sync" @click="handleAsync(scope.row)" label="同步"></pers-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-row>

        <div v-if="asyncDrawer">
            <el-drawer title="同步课件" :visible.sync="asyncDrawer" :direction="asyncDirection" :modal="false"
                :before-close="handleClose">
                <p style="font-size: 20px;font-weight: bold;text-align: center;">同步第1天内容至</p>
                <p style="font-size: 16px;text-align: center;">（注：如所选的那天已有内容，不会覆盖原有内容）</p>
                <el-row>

                    <el-table ref="multipleTable" :data="daysData" tooltip-effect="dark" row-key="id"
                        style="width: 100%" @selection-change="handleSelectionChange">
                        <el-table-column type="selection" width="55">
                        </el-table-column>
                        <el-table-column prop="day_name" label="全部">
                        </el-table-column>
                    </el-table>

                    <div style="margin-top: 30px;text-align: center;">
                        <el-button @click="closeDays">取消</el-button>
                        <el-button type="primary" @click="onSubmitDays">确定</el-button>
                    </div>
                </el-row>
            </el-drawer>
        </div>
        <!-- 显示添加创作弹框 -->
        <div v-if="showAddVisible">
            <show-create :visible.sync="showAddVisible" :current_day="type"
                :edit_create_data="edit_create_data"></show-create>
        </div>
        <!-- 显示添加 阅读、听力、录音等弹框 -->
        <div v-if="showAddCourseWareVisible">
            <show-add-course-ware :visible.sync="showAddCourseWareVisible" :task_type="task_type"
                :edit_task_courseware_arr="edit_task_courseware_arr"
                @handleSelectFiles="handleSelectFiles"></show-add-course-ware>
        </div>

    </div>
</template>
<script>
import {hasPermission, isShow} from '@/common/permission';
import { mapState, mapGetters, mapMutations } from 'vuex';
import ShowCreate from "@/views/kanke/exercises/task/components/ShowCreate";
import ShowAddCourseWare from "@/views/kanke/textbook/courseware/components/ShowAddCourseWare";
import PersButton from '../../../../../components/PersButton.vue';
export default {
    name: "ShowTaskList",
    props: {
        type: {
            type: String,
            default: 'taskFirstDay'  //taskFirstDay、taskSecondDay、taskThirdDay、taskFourthDay、taskFifthDay、taskSixthDay
        },
        modalKey: {
            type: String,
            default: 'taskFirstDay'
        }
    },
    components: {
        ShowCreate,
        ShowAddCourseWare,
        PersButton
    },

    data() {
        return {
            loading: false,
            showAddVisible: false,
            showAddCourseWareVisible: false,
            edit_task_courseware_arr: [],  //当前需要编辑的听力、阅读、录音等课件id
            task_type: 0,
            edit_create_data: {},
            activeKey: 'all',
            form: {},
            tableData: [],
            // taskDays: this.$store.state.assignTask.taskDays,
            //该数据当同步与state中数据一致
            daysData: [
                { 'day_name': '第1天', 'id': 'taskFirstDay' },
                { 'day_name': '第2天', 'id': 'taskSecondDay' },
                { 'day_name': '第3天', 'id': 'taskThirdDay' },
                { 'day_name': '第4天', 'id': 'taskFourthDay' },
                { 'day_name': '第5天', 'id': 'taskFifthDay' },
                { 'day_name': '第6天', 'id': 'taskSixthDay' },
            ],
            needAsync: {
                t_id: 0,
                content_id: 0,
                task_type: "",
                current_day: "",
                title: "",
                cover_url: "",
                unit_name: ""
            },
            all_num: 0,
            listen_num: 0,
            read_num: 0,
            record_num: 0,
            create_num: 0,
            multipleSelection: [],
            asyncDrawer: false,
            asyncDirection: 'rtl', //从右向左
        }
    },

    computed: {
        ...mapState(['taskDays']),
      taskDays(){
        return this.$store.state.assignTask.taskDays;
      }
    },
    watch: {
        type: {
            handler(newVal, oldVal) {
                if (newVal) {
                    this.init()
                }
            },
            immediate: true
        },

        taskDays: {
            handler(newVal, oldVal) {
                this.init();
                console.log('taskDays changed from', oldVal, 'to', newVal);
                // console.log('taskDays Data', this.$store.state.assignTask.taskDays[this.type]);

            },
            deep: true, //深度监听
            immediate: true  //立即执行
        },
        activeKey: {
            handler(newVal, oldVal) {
                console.log('label change from', oldVal, 'to', newVal);
                this.init();
            },
            immediate: true
        }
    },
    methods: {
        hasPermission,
        isShow,
        init() {
            this.loading = true

            console.log('task current_day', this.type);
            console.log('show task activeKey', this.activeKey);
            console.log('task all', this.$store.state.assignTask);

            let data = this.$store.state.assignTask.taskDays[this.type];
            this.listen_num = data.listen.length;
            this.read_num = data.read.length;
            this.record_num = data.record.length;
            this.create_num = data.create.length;
            this.all_num = this.listen_num + this.read_num + this.record_num + this.create_num;


            let mergerd = []
            if (this.activeKey == 'all') {
                mergerd = [...data.listen, ...data.read, ...data.record, ...data.create]
            } else {
                mergerd = data[this.activeKey]
            }
            console.log('mergerd', mergerd);

            //排序
            let mergerd_serialized =  JSON.stringify(mergerd);
            let mergerd_data = JSON.parse(mergerd_serialized);
            mergerd_data.sort(function (a,b) {
                return a.sort - b.sort;     //sort属性降序排序
                // return b.sort - a.sort;     //sort属性降序排序
            })

            console.log('排序后的子任务数据',mergerd);

            //测试 获取当前最大排序值
            this.$store.commit("GET_TASK_MAX_SORT",{'current_day':this.type})
            console.log('获取当前最大排序值',this.$store.state.assignTask.max_sort);


            this.tableData = [...mergerd_data];
            // this.tableData = [...mergerd];
            this.loading = false
        },

        handleRowkey(row) {
            return `${row.task_type}-${row.id}-${row.content_id}`
        },
        isArray(value) {
            return Array.isArray(value);
        },
        //选中标签
        handleClick(tab, event) {
            console.log('current tab', tab);
            this.activeKey = tab.name;
        },
        //关闭抽屉
        handleClose(done) {
            this.$confirm('确认关闭同步课件？')
                .then(_ => {
                    done();
                })
                .catch(_ => { });
        },
        handleSelectionChange(val) {
            console.log('当前选中行', val);
            this.multipleSelection = val
            console.log('multipleSelection val', this.multipleSelection);
        },
        sort(obj,type){
            console.log('显示当前排序参数',obj,type);
            let data = this.$store.state.assignTask.taskDays[this.type];
            //let mergerd = [...data.listen, ...data.read, ...data.record, ...data.create]
            let mergerd = [];
            if (this.activeKey == 'all') {
                mergerd = [...data.listen, ...data.read, ...data.record, ...data.create]
            } else {
                mergerd = data[this.activeKey]
            }
            //排序
            let mergerd_serialized =  JSON.stringify(mergerd);
            let mergerd_data = JSON.parse(mergerd_serialized);
            mergerd_data.sort(function (a,b) {
                return a.sort - b.sort;     //sort属性升序排序
                // return b.sort - a.sort;     //sort属性降序排序
            })
            //对排序值进行替换
            console.log('点击升降序后排序后的内容',mergerd_data);
            for(let i = 0;i < mergerd_data.length;i++){

                if(obj.id == mergerd_data[i].id && obj.content_id == mergerd_data[i].content_id){
                        if(i==0 && type == 1){
                            break; //升序 升无可升
                        }
                        if(i == mergerd_data.length - 1 && type == 2){
                            break; //降序 降无可降
                        }

                        if(type == 1){
                            //升序
                            let sort_asc = mergerd_data[i-1].sort;
                            let now_sort = mergerd_data[i].sort;

                            mergerd_data[i].sort = sort_asc;
                            mergerd_data[i-1].sort = now_sort;

                            this.$store.commit("EDIT_TASK_DAY",mergerd_data[i])
                            this.$store.commit("EDIT_TASK_DAY",mergerd_data[i-1])

                        }
                        if(type == 2){
                            //降序
                            let sort_desc = mergerd_data[i+1].sort;
                            let now_sort = mergerd_data[i].sort;

                            mergerd_data[i].sort = sort_desc;
                            mergerd_data[i+1].sort = now_sort;

                            this.$store.commit("EDIT_TASK_DAY",mergerd_data[i])
                            this.$store.commit("EDIT_TASK_DAY",mergerd_data[i+1])

                        }
                        break;
                }
            }
        },
        closeDays() {
            this.asyncDrawer = false;
        },
        onSubmitDays() {
            console.log('当前同步的任务类型', this.needAsync);
            console.log('当前选中需要同步天数', this.multipleSelection);

            if (this.multipleSelection.length > 0) {
                for (let i = 0; i < this.multipleSelection.length; i++) {

                    if (this.multipleSelection[i].id == this.needAsync.current_day) {
                        continue;
                    } else {
                        let str_needAsync =  JSON.stringify(this.needAsync);
                        str_needAsync = JSON.parse(str_needAsync);


                        str_needAsync = Object.assign(str_needAsync, { current_day: this.multipleSelection[i].id })
                        console.log('now async current_day data', str_needAsync);
                        this.$store.commit('EDIT_TASK_DAY', str_needAsync)
                        this.msgSuccess('同步成功');

                    }

                }
            }
            this.asyncDrawer = false;

        },
        handleEdit(obj) {
            //创作
            if (obj.task_type == 'create') {
                this.task_type = 4;
                this.edit_create_data = obj;
                this.showAddVisible = true;
            } else {
                //听力、阅读、录音
                // 添加的时候只在下标为零的添加, 
                this.edit_task_courseware_arr.splice(0, 1, obj);
                if (obj.task_type == 'listen') this.task_type = 1;
                if (obj.task_type == 'read') this.task_type = 2;
                if (obj.task_type == 'record') this.task_type = 3;
                this.showAddCourseWareVisible = true;
            }
            // this.$store.commit('SEARCH_TASK_Detail',{"id":obj.id,"current_day":obj.current_day,"task_type":obj.task_type})
            // console.log('SEARCH_TASK_Detail',this.$store.state.assignTask.searchTaskDetail);
        },
        handleDel(obj) {

            this.$confirm('确定要删除该任务?', '提示', {
                cancelButtonText: '取消',
                confirmButtonText: '确定',
                type: 'warning'
            }).then(() => {

                console.log('delete create data', obj);
                this.$store.commit('DELETE_TASK_DAY', { "id": obj.id,"content_id": obj.content_id, "current_day": obj.current_day, "task_type": obj.task_type })
                this.$message({ type: 'success', message: '删除成功!' });
                this.init();

            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消'
                });
            });

        },
        handleSelectFiles(val) {
            console.log('---当前选中的文件---', val);
            console.log('---当前任务类型', this.task_type);
            let task_type = this.getTaskType(this.task_type);
            if (val.length == 0) {
                this.msgError('未选择任何数据');
                return;
            }
            if (this.edit_task_courseware_arr.length > 0 && val.length > 1) {
                this.msgError('编辑只能选择一条数据请重新选择');
                return;
            }
            const isEdit = this.edit_task_courseware_arr.length > 0;
            val.map(item => {
                item.task_type = task_type;
                item.current_day = this.type;
                console.log('isEdit', isEdit)
                this.$store.commit('EDIT_TASK_DAY', item);
            })
            this.edit_task_courseware_arr = [];
            this.msgSuccess('保存成功');
        },
        //显示同步界面
        handleAsync(obj) {

            this.needAsync.task_type = obj.task_type;
            this.needAsync.current_day = obj.current_day;
            this.needAsync.title = obj.title;
            this.needAsync.cover_url = obj.cover_url;
            this.needAsync.id = obj.id;
            this.needAsync.t_id = obj.t_id;
            this.needAsync.content_id = obj.content_id;
            this.needAsync.sort = obj.sort;

            this.asyncDrawer = true;

            //获取选中按钮 同步提示
            this.$store.commit('SEARCH_SYNC_TASK_DAY', { "id": obj.id,"content_id": obj.content_id, "current_day": obj.current_day, "task_type": obj.task_type });

            let searchTaskDays = JSON.stringify(this.$store.state.assignTask.searchTaskDays);
            let searchDays = JSON.parse(searchTaskDays);
            console.log('searchDays', searchDays);

            //显示已选中数据
            this.$nextTick(() => {
                this.daysData.forEach(row => {
                    if (searchDays.includes(row.id)) {
                        //添加任务内容
                        row.day_name = row.day_name.substring(0, 3) + ' (已有任务内容)';
                        this.$refs.multipleTable.toggleRowSelection(row, true);
                    }
                });
            });

            console.log('current sync store data', searchDays);

        },
        getTaskType(task_type) {
            //1听力 2阅读 3.录音 4.创作
            switch (task_type) {
                case 1:
                    return "listen";
                    break;
                case 2:
                    return "read";
                    break;
                case 3:
                    return "record";
                    break;
                case 4:
                    return "create";
                    break;
                default:
                    break;
            }
        }
    }
}
</script>
<style lang="scss" scoped></style>